from math import sqrt
import time
import aiohttp
import asyncio

#协程程序
def coroutine_sqrt():
    total = 0
    length = 0
    while True:
        try:
            value = yield sqrt(total)
        except ZeroDivisionError:
            value = yield 0
        print(f"got send value {value}")
        total = value
        # total += value
        # length += 1

co_avg = coroutine_sqrt()
# print(co_avg)
next(co_avg)
# print(next(co_avg))
print(co_avg.send(2.5))
print(co_avg.send(4))

#asyncio异步程序
async def asy_requset():
    a = 0
    await asyncio.sleep(0.2)
    a += 1
    return a

task_array = []
for i in range(10):
    task_array.append(asy_requset())

#获取异步的事件队列
loop = asyncio.get_event_loop()
# loop.run_until_complete(asyncio.wait(task_array))
result_array = loop.run_until_complete(asyncio.gather(*task_array))
#loop.close()
print(result_array)

#aiohttp异步请求网站接口
url_array = ["https://www.taobao.com/"] * 2

async def requset_taobao(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            result = await response.text()
            # result = response.status
            return result

loop1 = asyncio.get_event_loop()
task_array = [requset_taobao(url) for url in url_array]
result = loop1.run_until_complete(asyncio.gather(*task_array))
loop1.close()
print(result)
